﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using SouthernLand.Common;
using SouthernLand.Common.Untilities;

namespace SouthernLand.WebMaster.RaoVat
{
    public partial class Categories : Page
    {
        private int CateID = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            //phan them danh muc
            btDelete.OnClientClick = "if (confirm('" + ResourceManager.GetString("DeleteConfirm") +
                                     "') == false) return false;";

            CateID = Globals.GetIntFromQueryString("CateID");

            if (CateID == 1)
                Response.Redirect(Globals.ApplicationPath + "WebMaster/Raovat/Categories.aspx");

            if (Request.QueryString["Action"] == "Edit")
            {
                btDelete.Visible = true;
                btSave.Text = ResourceManager.GetString("Update");
                if (!IsPostBack)
                    Load_GetCategoriesByCateID(CateID);
            }
            else
            {
                btDelete.Visible = false;
                btSave.Text = ResourceManager.GetString("AddNew");
            }

            if (!Page.IsPostBack)
                Load_TreeviewCategories();


            // xu ly de nodes duoc bung ra
            TreeNode n = findNode(CateID.ToString(), TreeCategories.Nodes);
            //LabelCurrentCategories.Text = n.Text; // page title
            while (n != null)
            {
                n.Expand();
                n = n.Parent;
            }
        }
        
        protected void Load_GetCategoriesByCateID(int CateID)
        {
            Common.BOL.NhaDat.Categories c;
            c = Common.BOL.NhaDat.Categories.GetCategoriesByID(CateID);
            txtTitle.Text = c.Title;
            txtTitle_en.Text = c.Title_en;
            txtDescription.Text = c.Description.Replace("<br>", "\n");
            txtDisplayOrder.Text = c.DisplayOrder.ToString();
            HPhotoFile.Value = c.ImageUrl; // luu lai hinh cu
            dlCategories.SelectedValue = c.ParentID.ToString();
        }

        protected string FilePhoto_Upload()
        {
            string strFileName = "";
            // kiem tra xem user co chon hinh dai dien ko
            if (PhotoFile.HasFile)
            {
                // kiem tra phan mo rong cua file co hop le hay khong
                string strExtension = Path.GetExtension(PhotoFile.FileName).ToUpper();
                if (strExtension == ".JPG" || strExtension == ".GIF" || strExtension == ".JPEG" ||
                    strExtension == ".PNG")
                {
                    // lay ten file de khong bi trung file + phan mo rong cua file can upload
                    strFileName = Common.Common.GetFileName() + Path.GetExtension(PhotoFile.FileName);

                    //duong dan tao save file Large
                    string strFilePathLarge = Request.PhysicalApplicationPath + "/UserUpload/Categories/" + strFileName;

                    //thuc hien save file Large len server
                    EnumUpload uploadLarge = FileProcess.UpLoadImage(PhotoFile, strFilePathLarge, 200);
                }
                else
                {
                    lblMsg.Text = "File bạn chọn upload không hợp lệ.";
                    strFileName = "";
                }
            }
            else
                return HPhotoFile.Value;

            return strFileName;
        }

        protected void btSave_Click(object sender, EventArgs e)
        {
            var cate = new Common.BOL.NhaDat.Categories();
            cate.CateID = CateID;
            cate.AddedDate = DateTime.Now;
            cate.AddedBy = Globals.CurrentUserName;
            cate.AppKey = "";
            cate.ImageUrl = FilePhoto_Upload();
            cate.Description = txtDescription.Text.Replace(Environment.NewLine, "<br>");
            cate.Title = txtTitle.Text;
            cate.Title_en = txtTitle_en.Text;
            cate.DisplayOrder = Convert.ToInt32(txtDisplayOrder.Text);
            if (dlCategories.SelectedItem.Value != "")
                cate.ParentID = Convert.ToInt32(dlCategories.SelectedItem.Value);
            else
                cate.ParentID = ConvertUtility.ToInt32(eCategory.DanhMucTin);

            if (Globals.GetStringFromQueryString("Action") == eAction.Edit.ToString())
            {
                // no khong the tham chieu den chinh no
                if (CateID == ConvertUtility.ToInt32(dlCategories.SelectedItem.Value))
                    Response.Redirect(Globals.ApplicationPath + "WebMaster/Raovat/Categories.aspx?CateID=" + CateID);
                else
                    Common.BOL.NhaDat.Categories.Update(cate);
            }
            else
            {
                CateID = Common.BOL.NhaDat.Categories.Insert(cate);
            }


            Response.Redirect(Globals.ApplicationPath + "WebMaster/Raovat/Categories.aspx?CateID=" + CateID);
        }

        protected void btDelete_Click(object sender, EventArgs e)
        {
            bool value = Common.BOL.NhaDat.Categories.Delete(CateID);
            if (value == false)
                Response.Write(
                    "<script> alert('Bạn không được phép xóa Record này vì liên quan đến hệ thống.') </script>");
            else
                Response.Redirect(Globals.ApplicationPath + "WebMaster/Raovat/Categories.aspx");
        }

        protected void btCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Globals.ApplicationPath + "WebMaster/Raovat/Categories.aspx");
        }
        
        protected void Load_TreeviewCategories()
        {
            // phan load danh muc vao treeview
            if (!IsPostBack)
            {
                // populate the TreeView from scratch
                TreeCategories.Nodes.Clear();
                List<Common.BOL.NhaDat.Categories> rootCategories =
                    Common.BOL.NhaDat.Categories.GetCategoriesByParentID((int) eCategory.DanhMucTin);
                    // get root level ones
                foreach (Common.BOL.NhaDat.Categories c in rootCategories)
                {
                    TreeNode newNode;
                    newNode = new TreeNode(
                        (Globals.LangVietNam()) ? c.Title + " (" + c.DisplayOrder + ")" : c.Title_en,
                        c.CateID.ToString());
                    newNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                    newNode.NavigateUrl = Globals.ApplicationPath +
                                          "WebMaster/Raovat/Categories.aspx?Action=Edit&Page=Categories&CateID=" +
                                          c.CateID;
                    TreeCategories.Nodes.Add(newNode);
                    populateCategoriesNode(newNode);
                }
            }
        }

        private void populateCategoriesNode(TreeNode n)
        {
            List<Common.BOL.NhaDat.Categories> ChildMenu =
                Common.BOL.NhaDat.Categories.GetCategoriesByParentID(Convert.ToInt32(n.Value));

            if (ChildMenu.Count == 0) // base case: leaf Categories 
            {
                return;
            }
            else //  recursive case : expand to show sub-categories
            {
                foreach (Common.BOL.NhaDat.Categories c in ChildMenu)
                {
                    TreeNode newNode;
                    newNode = new TreeNode((Globals.LangVietNam()) ? c.Title : c.Title_en, c.CateID.ToString());
                    newNode.Collapse();
                    newNode.ToolTip = c.CateID.ToString();
                    newNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                    newNode.NavigateUrl = Globals.ApplicationPath +
                                          "WebMaster/Raovat/Categories.aspx?Action=Edit&Page=Categories&CateID=" +
                                          c.CateID;
                    n.ChildNodes.Add(newNode);
                    populateCategoriesNode(newNode);
                }
            }
        }
        
        private TreeNode findNode(string value, TreeNodeCollection nodes)
        {
            foreach (TreeNode n in nodes)
            {
                if (n.Value == value)
                {
                    return n;
                }
                else // search n's child nodes
                {
                    TreeNode nChild = findNode(value, n.ChildNodes);
                    if (nChild != null)
                        return nChild;
                }
            }
            return null;
        }
    }
}